/**
 * Created by Weizehua on 2017/1/18.
 */
import {Singleton, Injector} from "ts.di";
import {createConnection, ConnectionOptions, Connection, Table, EntityOptions, AbstractTable} from "typeorm";

@Singleton()
export class Database {
    async connect(options: ConnectionOptions): Promise<Connection> {
        let o:any = {};
        for(let k of Object.keys(options))
        {
            o[k] = options[k]
        }
        o.autoSchemaSync = true;
        o.entities = Database.tables;
        this.connection = await createConnection(o);
        Injector.setSingleton(Connection, this.connection);
        return this.connection;
    }

    static tableDecoratorFactor(name?: string, options?: EntityOptions): Function {
        return <TFunction extends Function>(target: TFunction): void => {
            Database.tables.push(target);
            return Table(name, options)(target);
        }
    }

    static abstractTableDecoratorFactor(): Function {
        return <TFunction extends Function>(target: TFunction): void => {
            Database.tables.push(target);
            return AbstractTable()(target);
        }
    }

    connection: Connection;
    static tables = [];
}

export let PETable = Database.tableDecoratorFactor;

export let PEAbstractTable = Database.abstractTableDecoratorFactor;
